#include <jni.h>
#include <GLES3/gl3.h>

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL
surfCreated(JNIEnv *, jobject, jint color) {
    GLfloat redF = ((color >> 16) & 0xFF) * 1.0f / 255;
    GLfloat greenF = ((color >> 8) & 0xFF) * 1.0f / 255;
    GLfloat blueF = (color & 0xFF) * 1.0f / 255;
    GLfloat alphaF = ((color >> 24) & 0xFF) * 1.0f / 255;
    glClearColor(redF, greenF, blueF, alphaF);
}

JNIEXPORT void JNICALL
surfChanged(JNIEnv *, jobject, jint w, jint h) {
    glViewport(0, 0, w, h);
}

JNIEXPORT void JNICALL
drawFrame(JNIEnv *, jobject) {
    glClear(GL_COLOR_BUFFER_BIT);
}

#ifdef __cplusplus
}
#endif

JNINativeMethod methods[] = {
        {"surfCreated", "(I)V",  (void *) (surfCreated)},
        {"surfChanged", "(II)V", (void *) (surfChanged)},
        {"drawFrame",   "()V",   (void *) (drawFrame)},
};

JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env = nullptr;
    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK)return -1;
    jclass clz = env->FindClass("com/andova/egl/EGL");
    if (env->RegisterNatives(clz, methods, sizeof(methods) / sizeof(methods[0])) < 0)return -1;
    return JNI_VERSION_1_6;
}

JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) {
}